package com.wxfire;

import com.wxfire.entity.User;
import com.wxfire.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.MediaType;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据连接信息存放在远程 nacos中
 */
@RestController
public class Homework {

    @Autowired
    DataSource dataSource;

    @Autowired
    UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 基本信息
     * @return
     */
    @RequestMapping(value = "info", produces = MediaType.APPLICATION_XML_VALUE)
    public Object info() {
        Map<String,Object> result =new HashMap<>();
        result.put("redis:",redisTemplate != null);
        result.put("db:",userMapper.selectAll());
        return result;
    }

    /**
     * 带redis缓存的查询
     * @return
     */
    @RequestMapping(value = "list", produces = MediaType.APPLICATION_JSON_VALUE)
    public Object list() {
        String key ="users";
        List users = redisTemplate.opsForList().range(key, 0, -1);
        if(users.isEmpty()){
            users = userMapper.selectAll();
            redisTemplate.opsForList().leftPushAll(key,users);
            return users;
        }
        return users;
    }

    /**
     * 添加数据
     * @return
     */
    @GetMapping("/add")
    public Object add() {
        User user = new User();
        user.setName("testuser");
        user.setPass("1111");
        userMapper.insert(user);
        return userMapper.selectAll();
    }

    /**
     * 更新数据
     * @param id
     * @param name
     * @return
     */
    @GetMapping("/update")
    public Object update(@RequestParam("id") Long id,@RequestParam("name") String name) {
        User user = new User();
        user.setId(id);
        user.setName(name);
        userMapper.insert(user);
        return userMapper.selectAll();
    }

    /**
     * 删除数据
     * @param id
     * @return
     */
    @GetMapping("/delete")
    public Object delete(@RequestParam("id") Long id) {
        userMapper.delete(id);
        return userMapper.selectAll();
    }
}
